package com.heqiang.spring.core.io;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import com.heqiang.spring.BeansException;
import com.heqiang.spring.bean.PropertyValue;
import com.heqiang.spring.config.BeanDefinition;
import com.heqiang.spring.config.BeanDefinitionRegistry;
import com.heqiang.spring.config.BeanReference;
import com.heqiang.spring.core.io.loader.ResourceLoader;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import java.io.InputStream;

public class XmlBeanDefinitionReader extends AbstractBeanDefinitionReader {

    public XmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
        super(registry);
    }

    public XmlBeanDefinitionReader(BeanDefinitionRegistry registry, ResourceLoader resourceLoader) {
        super(registry,resourceLoader);
    }

    @Override
    public void loadBeanDefinitions(Resource resource) throws BeansException {
        try {
            try (InputStream inputStream = resource.getInputStream()) {
                doLoadBeanDefinitions(inputStream);
            }
        } catch (Exception e) {
            throw new BeansException("IOException parsing XML document from " + resource, e);
        }
    }

    @Override
    public void loadBeanDefinitions(Resource... resources) throws BeansException {
        for (Resource resource : resources) {
            loadBeanDefinitions(resource);
        }
    }

    @Override
    public void loadBeanDefinitions(String location) throws BeansException {
        ResourceLoader loader = getResourceLoader();
        Resource resource = loader.getResource(location);
        loadBeanDefinitions(resource);

    }

    @Override
    public void loadBeanDefinitions(String... locations) throws BeansException {
        for (String location : locations) {
            loadBeanDefinitions(location);
        }
    }


    protected void doLoadBeanDefinitions(InputStream inputStream) throws Exception {
        Document doc = XmlUtil.readXML(inputStream);
        Element root = doc.getDocumentElement();
        NodeList nodeLists = root.getChildNodes();
        for (int i =0 ; i<nodeLists.getLength();i++) {
            if (!(nodeLists.item(i) instanceof Element)) {
                continue;
            }
            if (!"bean".equals(nodeLists.item(i).getNodeName())) {
                continue;
            }
            Element bean = (Element) nodeLists.item(i);
            String id = bean.getAttribute("id");
            String name = bean.getAttribute("name");
            String className = bean.getAttribute("class");
            String initMethodName = bean.getAttribute("init-method");
            String destroyMethodName = bean.getAttribute("destroy-method");
            // 获取 Class，方便获取类中的名称
            Class<?> clazz = Class.forName(className);
            //优先级：id>name
            String beanName = StrUtil.isNotEmpty(id) ? id : name;
            if (StrUtil.isEmpty(beanName)) {
                beanName = StrUtil.lowerFirst(clazz.getSimpleName());
            }
            //定义Bean
            BeanDefinition beanDefinition = new BeanDefinition(clazz);
            beanDefinition.setInitMethodName(initMethodName);
            beanDefinition.setDestroyMethodName(destroyMethodName);
            //读取属性并填充
            for (int j = 0; j < bean.getChildNodes().getLength();j++) {
                if (!(bean.getChildNodes().item(j) instanceof Element)) {
                    continue;
                }
                if (!"property".equals(bean.getChildNodes().item(j).getNodeName())) {
                    continue;
                }
                Element property = (Element) bean.getChildNodes().item(j);
                String attName = property.getAttribute("name");
                String attValue = property.getAttribute("value");
                String attRef = property.getAttribute("ref");

                Object value = StrUtil.isNotEmpty(attRef)?new BeanReference(attRef) : attValue;

                PropertyValue propertyValue = new PropertyValue(attName,value);
                beanDefinition.getPropertyValues().addProperValue(propertyValue);
            }
            if (getRegistry().containsBeanDefition(beanName)) {
                    throw new BeansException("重复注册相同的bean");
            }
            getRegistry().registerBeanDefinition(beanName,beanDefinition);
        }
    }
}
